package com.code.generator.code.impl;

import com.code.generator.context.GeneratorContext;
import com.code.exception.CodeGenerateException;
import com.code.generator.code.CodeGenerator;
import org.apache.commons.lang3.StringUtils;

import java.io.File;

public abstract class AbstractGenerator<T extends GeneratorContext> implements CodeGenerator<T> {

    private static final String FILE_SEPARATOR = System.getProperty("file.separator");

    protected File buildFile(T context, String parent, String packageName, String fileName) {
        if (StringUtils.isBlank(packageName)) {
            throw new CodeGenerateException("包名不能为空!");
        }

        if (StringUtils.isBlank(fileName)) {
            throw new CodeGenerateException("文件名不能为空!");
        }

        StringBuilder builder = new StringBuilder(context.destination());
        builder.append(FILE_SEPARATOR);

        if (StringUtils.isNotBlank(parent)) {
            builder.append(parent);
            builder.append(FILE_SEPARATOR);
        }

        builder.append(packageName.replace(".", FILE_SEPARATOR));

        String path = builder.toString();

        File file = new File(path);
        if (!file.exists()) {
            boolean success = file.mkdirs();
            if (!success) {
                throw new RuntimeException("创建目录失败!");
            }
        }
        return new File(path + FILE_SEPARATOR + fileName);
    }

}
